import dd from "gdt-jsapi";
import axios from "axios";
let devhttp="http://23.99.221.59:7010"
let prodhttp="http://23.210.52.90:80";
let prodFlag=true;//true是生产环境false测试环境
let url=prodFlag?prodhttp:devhttp
export const getNewAuthCode = (authcode, appKey) => {
  //用authcode换Token的接口

  return axios.post(url+`/unionauth/token/IdentityToken?authCode=${authcode}&appKey=${appKey}`)
    .then(response => {
      return response;
    })
}
export const checkAuthCode = async (urlAuthCode, urlName, appKey) => {
 return new Promise(async (resolve, reject) => {
    if (urlAuthCode) {
      //用authcode换Token的接口
      const res = await getNewAuthCode(urlAuthCode, appKey);
      if (res.data?.code == 500) {
        goLogin(urlName, appKey)
      } else {
        let tokenData = res.data;
        console.log(tokenData, "用authcode换token")
        localStorage.setItem('dcqc-tk', tokenData.data);
        resolve(tokenData.data);
    
      }
    } else {
      let code;
      try {
        const res = await dd.getAuthCode({});
        code = res.auth_code;
        console.log(code, "Token过期>>>>>>>>>>auth_code")
        const resData = await getNewAuthCode(code, appKey);
        console.log(resData, "Token过期>>>>>>>>>>resData")
        if (resData.data?.code == 500) {
          goLogin(urlName, appKey)
        } else {
          let tokenData = resData.data;
          console.log(tokenData, "Token过期用authcode换token")
          resolve(tokenData.data) 
        }
      }
      catch (error) {
        console.log(error, "cuowu")
        goLogin(urlName, appKey)
      }
    }
    
  })
 
}

const goLogin = (urlName, appKey) => {
  console.log(urlName, appKey, ">>>>>>>>>>>appkey");
  window.location.href = url+`/auth/login?url=${encodeURIComponent(urlName)}&appKey=${appKey}`;
}

//检验token有没有过期
export const checkToken = async (urlName, token, appKey, urlAuthCode) => {
  const response = await axios.get(url+`/unionauth/token/checkToken/${token}/${appKey}`)
  const res = response.data;
  console.log(res, "判断返回的data是不是false");
  if (res.data == false || res.code === 500) {
    console.log('token过期调用checkAuthCode方法:',)
    const data = await checkAuthCode(urlAuthCode, urlName, appKey);
    console.log("返回的promise: ", data)
    return data;
    
  } else {
    console.log('token未过期直接返回token:', token)
    return token
  }

}

// 获取url上的queryString
export const getUrlParams = (url) => {
  const params = {};
  const urlSplitList = url.split("?");
  if (urlSplitList && urlSplitList.length) {
    const paramStringList = urlSplitList.pop();
    if (paramStringList) {
      let paramStrings = paramStringList.split("&");
      if (paramStrings && paramStrings.length) {
        paramStrings.forEach((paramString) => {
          const [key, value] = paramString.split("=");
          params[key] = value;
        });
      }
    }
  }
  return params
}